import { reactive, toRefs,onMounted,computed } from "vue";

import {PaginationProps} from "ant-design-vue/lib";
import { message } from 'ant-design-vue';
import {paginationProps} from "ant-design-vue/lib/pagination/Pagination";
interface Options{
    pagination:paginationProps
}

export const useTablePagination = (api:any,searchParams = {},
                                   loading=false,option:Options={}) => {
    const state = reactive({
        tableData: [],
        searchParams,
        searchInitParams:{},
        pagination:{
            // 当前页数
            current: 1,
            // 每页显示条数
            pageSize: 10,
            // 总条数
            total: 0,
            ...option.pagination
        },
        // 是否加载中
        loading,
    });
    const pageParam = computed({
        get: () => {
            return {
                pageNo: state.pagination.current,
                pageSize: state.pagination.pageSize
            };
        }
    });
    const getTableData = ()=>{

        const queryParams = Object.assign(pageParam,searchParams);
        state.loading = true;
        api(queryParams).then(res=>{
            state.tableData = res.result.records;
            state.pagination.total = res.result.total
            state.loading = false;
        })
    }
    const search = () => {
        state.pagination.current = 1;
        state.pagination.total = 0
        getTableData();
    };
    const reset = () => {
        state.searchParams = {};
        // 重置搜索表单的时，如果有默认搜索参数，则重置默认的搜索参数
        Object.keys(state.searchInitParam).forEach(key => {
            state.searchParams[key] = state.searchInitParams[key];
        });
        search()
    };
    const paginationChange = ({pagination})=>{
        state.pagination.current = pagination.current;
        state.pagination.pageSize = pagination.pageSize;
        getTableData();
    }
    onMounted(() => {
        getTableData();
    });
    return {
        ...toRefs(state),
        search,
        reset,
        paginationChange
    };
};
